<template>
  <div class="app-detail-page">
    <div class="page-header">
      <a-page-header :title="appInfo.appName" @back="handleBack">
        <template #extra>
          <a-space>
            <a-button v-if="canEdit" @click="handleEdit">
              <EditOutlined />
              编辑
            </a-button>
            <a-button v-if="canExport" @click="handleExport">
              <DownloadOutlined />
              导出对话
            </a-button>
            <a-button type="primary" @click="handleChat">
              <MessageOutlined />
              对话
            </a-button>
            <a-button v-if="appInfo.deployKey" @click="handleVisit">
              <LinkOutlined />
              访问
            </a-button>
          </a-space>
        </template>
      </a-page-header>
    </div>

    <div class="detail-content">
      <a-row :gutter="24">
        <!-- 左侧应用信息 -->
        <a-col :xs="24" :lg="16">
          <a-card title="应用信息" class="info-card">
            <div class="app-info">
              <div class="app-cover">
                <img v-if="appInfo.cover" :src="appInfo.cover" :alt="appInfo.appName" />
                <div v-else class="cover-placeholder">
                  <AppstoreOutlined />
                </div>
              </div>
              <div class="app-details">
                <h2>{{ appInfo.appName }}</h2>
                <div class="app-meta">
                  <a-tag :color="getCodeTypeColor(appInfo.codeGenType)">
                    {{ getTypeName(appInfo.codeGenType) }}
                  </a-tag>
                  <a-tag v-if="appInfo.priority === 100" color="gold">
                    <StarFilled />
                    精选应用
                  </a-tag>
                  <a-tag v-if="appInfo.deployKey" color="green">
                    <LinkOutlined />
                    已部署
                  </a-tag>
                  <a-tag :color="appInfo.isPublic === 1 ? 'blue' : 'default'">
                    <EyeOutlined v-if="appInfo.isPublic === 1" />
                    <EyeInvisibleOutlined v-else />
                    {{ appInfo.isPublic === 1 ? '公开' : '私有' }}
                  </a-tag>
                </div>
                <div class="app-description">
                  <h4>初始提示词</h4>
                  <p>{{ appInfo.initPrompt || '暂无描述' }}</p>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 预览区域 -->
          <a-card title="应用预览" class="preview-card">
            <div class="preview-container">
              <div v-if="!previewUrl" class="preview-placeholder">
                <AppstoreOutlined />
                <p>暂无预览</p>
                <a-button type="primary" @click="handleChat"> 开始对话生成 </a-button>
              </div>
              <iframe v-else :src="previewUrl" class="preview-iframe" frameborder="0"></iframe>
            </div>
          </a-card>
        </a-col>

        <!-- 右侧统计信息 -->
        <a-col :xs="24" :lg="8">
          <!-- 创建者信息 -->
          <a-card title="创建者" class="creator-card">
            <div v-if="appInfo.user" class="creator-info">
              <a-avatar :src="appInfo.user.userAvatar" :size="64">
                {{ appInfo.user.userName?.charAt(0) }}
              </a-avatar>
              <div class="creator-details">
                <div class="creator-name">
                  <h4>{{ appInfo.user.userName || '未设置昵称' }}</h4>
                  <a-tag v-if="appInfo.user.userRole === 'admin'" color="gold" size="small">
                    <CrownOutlined />
                    管理员
                  </a-tag>
                </div>
                <p class="creator-account">{{ appInfo.user.userAccount }}</p>
                <p v-if="appInfo.user.email" class="creator-email">{{ appInfo.user.email }}</p>
                <p v-if="appInfo.user.userProfile" class="creator-profile">{{ appInfo.user.userProfile }}</p>
                <p v-if="appInfo.user.shareCode" class="creator-share">邀请码: {{ appInfo.user.shareCode }}</p>
              </div>
            </div>
            <div v-else class="no-creator">
              <p>创建者信息不可用</p>
            </div>
          </a-card>

          <!-- 应用统计 -->
          <a-card title="应用信息" class="stats-card">
            <div class="stats-grid">
              <!-- 应用ID -->
              <div class="stat-item">
                <div class="stat-icon">
                  <AppstoreOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-label">应用ID</div>
                  <div class="stat-value" :title="appInfo.id">
                    {{ formatAppId(appInfo.id) }}
                  </div>
                </div>
              </div>

              <!-- 应用类型 -->
              <div class="stat-item">
                <div class="stat-icon type-icon" :class="getTypeClass(appInfo.codeGenType)">
                  <component :is="getTypeIcon(appInfo.codeGenType)" />
                </div>
                <div class="stat-content">
                  <div class="stat-label">应用类型</div>
                  <div class="stat-value">{{ getTypeName(appInfo.codeGenType) }}</div>
                </div>
              </div>

              <!-- 公开状态 -->
              <div class="stat-item">
                <div class="stat-icon" :class="appInfo.isPublic === 1 ? 'public-icon' : 'private-icon'">
                  <EyeOutlined v-if="appInfo.isPublic === 1" />
                  <EyeInvisibleOutlined v-else />
                </div>
                <div class="stat-content">
                  <div class="stat-label">状态</div>
                  <div class="stat-value">
                    <a-tag :color="appInfo.isPublic === 1 ? 'blue' : 'default'" size="small">
                      {{ appInfo.isPublic === 1 ? '公开' : '私有' }}
                    </a-tag>
                  </div>
                </div>
              </div>

              <!-- 优先级 -->
              <div class="stat-item">
                <div class="stat-icon priority-icon">
                  <StarFilled v-if="appInfo.priority === 100" />
                  <StarOutlined v-else />
                </div>
                <div class="stat-content">
                  <div class="stat-label">优先级</div>
                  <div class="stat-value">
                    <a-tag v-if="appInfo.priority === 100" color="gold" size="small">
                      <StarFilled />
                      精选
                    </a-tag>
                    <span v-else>{{ appInfo.priority || 0 }}</span>
                  </div>
                </div>
              </div>

              <!-- 创建时间 -->
              <div class="stat-item">
                <div class="stat-icon time-icon">
                  <ClockCircleOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-label">创建时间</div>
                  <div class="stat-value small">{{ formatTime(appInfo.createTime) }}</div>
                </div>
              </div>

              <!-- 最后编辑 -->
              <div class="stat-item">
                <div class="stat-icon edit-icon">
                  <EditOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-label">最后编辑</div>
                  <div class="stat-value small">{{ formatTime(appInfo.editTime) }}</div>
                </div>
              </div>

              <!-- 部署信息 -->
              <div v-if="appInfo.deployKey" class="stat-item">
                <div class="stat-icon deploy-icon">
                  <LinkOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-label">部署时间</div>
                  <div class="stat-value small">{{ formatTime(appInfo.deployedTime) }}</div>
                </div>
              </div>

              <div v-if="appInfo.deployKey" class="stat-item">
                <div class="stat-icon">
                  <CodeOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-label">部署标识</div>
                  <div class="stat-value" :title="appInfo.deployKey">
                    {{ formatDeployKey(appInfo.deployKey) }}
                  </div>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 公开状态管理（仅创建者和管理员可见） -->
          <a-card v-if="canEdit" title="应用设置" class="settings-card">
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-title">
                  <SettingOutlined />
                  公开状态
                </div>
                <div class="setting-desc">
                  {{ appInfo.isPublic === 1 ? '应用已在应用广场公开展示，其他用户可以浏览使用' : '应用仅自己可见，开启后将在应用广场展示给所有用户' }}
                </div>
              </div>
              <a-switch 
                :checked="appInfo.isPublic === 1" 
                @change="handlePublicToggle"
                :loading="publicToggleLoading"
                checked-children="公开"
                un-checked-children="私有"
                size="default"
              />
            </div>
          </a-card>

          <!-- 操作区域 -->
          <a-card title="操作" class="actions-card">
            <a-space direction="vertical" style="width: 100%">
              <a-button type="primary" block @click="handleChat">
                <MessageOutlined />
                开始对话
              </a-button>
              <a-button v-if="canEdit" block @click="handleEdit">
                <EditOutlined />
                编辑应用
              </a-button>
              <a-button v-if="canExport" block @click="handleExport">
                <DownloadOutlined />
                导出对话记录
              </a-button>
              <a-button v-if="appInfo.deployKey" block @click="handleVisit">
                <LinkOutlined />
                访问应用
              </a-button>
              <a-button v-if="canDelete" block danger @click="handleDelete">
                <DeleteOutlined />
                删除应用
              </a-button>
            </a-space>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 导出对话记录弹窗 -->
    <ExportChatHistoryModal
      v-model:open="exportModalVisible"
      :app-id="appId"
      :app-name="appInfo.appName"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  EditOutlined,
  MessageOutlined,
  LinkOutlined,
  DeleteOutlined,
  AppstoreOutlined,
  StarFilled,
  DownloadOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  CrownOutlined,
  SettingOutlined,
  StarOutlined,
  ClockCircleOutlined,
  CodeOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { getAppById1, deleteApp1, updateAppPublicStatus } from '@/api/yingyongjiekou'
import { getAppById, deleteApp } from '@/api/guanliyuanjiekou'
import ExportChatHistoryModal from '@/components/ExportChatHistoryModal.vue'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

const appId = computed(() => route.params.appId as string)

// 是否为管理员
const isAdmin = computed(() => loginUserStore.loginUser.userRole === 'admin')

// 应用信息
const appInfo = reactive<API.AppVO>({})

// 导出弹窗显示状态
const exportModalVisible = ref(false)

// 公开状态切换加载状态
const publicToggleLoading = ref(false)

// 预览URL
const previewUrl = computed(() => {
  if (appInfo.codeGenType && appInfo.id && appInfo.codeGenType !== 'vue_project') {
    return `http://localhost:8080/api/static/${appInfo.codeGenType}_${appInfo.id}/`
  }else {
    return `http://localhost:8080/api/static/${appInfo.codeGenType}_${appInfo.id}/dist/index.html`
  }
  return ''
})

// 权限判断
const canEdit = computed(() => {
  return isAdmin.value || loginUserStore.loginUser.id === appInfo.userId
})

const canDelete = computed(() => {
  return isAdmin.value || loginUserStore.loginUser.id === appInfo.userId
})

const canExport = computed(() => {
  return isAdmin.value || loginUserStore.loginUser.id === appInfo.userId
})

// 加载应用信息
const loadAppInfo = async () => {
  try {
    const response = isAdmin.value
      ? await getAppById({ id: appId.value })
      : await getAppById1({ id: appId.value })

    if (response.data.code === 200 && response.data.data) {
      Object.assign(appInfo, response.data.data)
    } else {
      message.error('获取应用信息失败')
      router.push('/')
    }
  } catch (error) {
    message.error('获取应用信息失败')
    console.error(error)
    router.push('/')
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 编辑应用
const handleEdit = () => {
  router.push(`/app/edit/${appId.value}`)
}

// 开始对话
const handleChat = () => {
  router.push(`/app/chat/${appId.value}`)
}

// 导出对话记录
const handleExport = () => {
  if (!canExport.value) return
  exportModalVisible.value = true
}

// 访问应用
const handleVisit = () => {
  if (appInfo.deployKey) {
    window.open(`http://localhost:8080/api/static/${appInfo.deployKey}/`, '_blank')
  }
}

// 删除应用
const handleDelete = () => {
  if (!canDelete.value) return

  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个应用吗？此操作不可恢复。',
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = isAdmin.value
          ? await deleteApp({ id: appId.value })
          : await deleteApp1({ id: appId.value })

        if (response.data.code === 200) {
          message.success('删除成功')
          router.push('/')
        } else {
          message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        message.error('删除失败')
        console.error(error)
      }
    }
  })
}

// 公开状态切换
const handlePublicToggle = async (checked: boolean) => {
  if (!canEdit.value) return

  publicToggleLoading.value = true
  try {
    const response = await updateAppPublicStatus({
      appId: appId.value,
      isPublic: checked ? 1 : 0
    })

    if (response.data.code === 200) {
      message.success('公开状态更新成功')
      appInfo.isPublic = checked ? 1 : 0
    } else {
      message.error(response.data.message || '更新公开状态失败')
    }
  } catch (error) {
    message.error('更新公开状态失败')
    console.error(error)
  } finally {
    publicToggleLoading.value = false
  }
}

// 获取代码类型颜色
const getCodeTypeColor = (type?: string) => {
  switch (type) {
    case 'react':
      return 'blue'
    case 'vue':
      return 'green'
    case 'html':
      return 'orange'
    default:
      return 'default'
  }
}

// 获取代码类型名称
const getTypeName = (type?: string) => {
  switch (type) {
    case 'react':
      return 'React'
    case 'vue':
      return 'Vue'
    case 'html':
      return 'HTML'
    default:
      return type || '未知'
  }
}

// 获取代码类型图标
const getTypeIcon = (type?: string) => {
  switch (type) {
    case 'react':
      return 'CodeOutlined'
    case 'vue':
      return 'CodeOutlined'
    case 'html':
      return 'CodeOutlined'
    default:
      return 'CodeOutlined'
  }
}

// 获取代码类型图标类名
const getTypeClass = (type?: string) => {
  switch (type) {
    case 'react':
      return 'react-icon'
    case 'vue':
      return 'vue-icon'
    case 'html':
      return 'html-icon'
    default:
      return ''
  }
}

// 格式化应用ID
const formatAppId = (id?: string) => {
  if (!id) return 'N/A'
  if (id.length <= 16) return id
  return id.substring(0, 8) + '...' + id.substring(id.length - 8)
}

// 格式化部署标识
const formatDeployKey = (key?: string) => {
  if (!key) return 'N/A'
  if (key.length <= 16) return key
  return key.substring(0, 8) + '...' + key.substring(key.length - 8)
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return '未知'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadAppInfo()
})
</script>

<style scoped>
.app-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.page-header {
  margin-bottom: 16px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card,
.preview-card,
.creator-card,
.stats-card,
.actions-card,
.settings-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}

.info-card :deep(.ant-card-body),
.preview-card :deep(.ant-card-body),
.creator-card :deep(.ant-card-body),
.stats-card :deep(.ant-card-body),
.actions-card :deep(.ant-card-body),
.settings-card :deep(.ant-card-body) {
  padding: 16px;
}

.app-info {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.app-cover {
  width: 160px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
  flex-shrink: 0;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  color: #d9d9d9;
  font-size: 32px;
}

.app-details {
  flex: 1;
}

.app-details h2 {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
}

.app-meta {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.app-description h4 {
  margin: 0 0 6px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.app-description p {
  margin: 0;
  color: #666;
  line-height: 1.5;
  font-size: 14px;
}

.preview-container {
  height: 700px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
}

.preview-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  color: #999;
  gap: 12px;
}

.preview-placeholder :deep(.anticon) {
  font-size: 36px;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.creator-details {
  display: flex;
  flex-direction: column;
}

.creator-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.creator-name h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.creator-account {
  margin: 2px 0;
  color: #666;
  font-size: 13px;
}

.creator-email {
  margin: 2px 0;
  color: #666;
  font-size: 13px;
}

.creator-profile {
  margin: 2px 0;
  color: #666;
  font-size: 13px;
}

.creator-share {
  margin-top: 4px;
  color: #666;
  font-size: 13px;
}

.no-creator {
  text-align: center;
  color: #999;
  padding: 16px 0;
}

.stats-card {
  margin-bottom: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
  padding: 8px 0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
  border: 1px solid #eee;
}

.stat-icon {
  font-size: 20px;
  color: #555;
}

.type-icon {
  font-size: 22px;
}

.react-icon {
  color: #1890ff;
}

.vue-icon {
  color: #4caf50;
}

.html-icon {
  color: #ff9800;
}

.public-icon {
  color: #1890ff;
}

.private-icon {
  color: #d9d9d9;
}

.priority-icon {
  font-size: 18px;
}

.time-icon {
  font-size: 18px;
}

.edit-icon {
  font-size: 18px;
}

.deploy-icon {
  font-size: 18px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 2px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  word-break: break-all;
}

.small {
  font-size: 12px;
}

.settings-card {
  margin-bottom: 16px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info {
  flex: 1;
  margin-right: 16px;
}

.setting-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.setting-desc {
  margin-top: 2px;
  font-size: 12px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-detail-page {
    padding: 0 12px;
  }

  .page-header {
    margin-bottom: 12px;
  }

  .detail-content {
    gap: 12px;
  }

  .info-card,
  .preview-card,
  .creator-card,
  .stats-card,
  .actions-card,
  .settings-card {
    margin-bottom: 12px;
  }

  .info-card :deep(.ant-card-body),
  .preview-card :deep(.ant-card-body),
  .creator-card :deep(.ant-card-body),
  .stats-card :deep(.ant-card-body),
  .actions-card :deep(.ant-card-body),
  .settings-card :deep(.ant-card-body) {
    padding: 12px;
  }

  .app-info {
    flex-direction: column;
    gap: 12px;
  }

  .app-cover {
    width: 100%;
    height: 160px;
  }

  .creator-info {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }

  .preview-container {
    height: 320px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
    gap: 8px;
    padding: 4px 0;
  }

  .stat-item {
    gap: 8px;
    padding: 8px 10px;
  }

  .stat-icon {
    font-size: 18px;
  }

  .type-icon {
    font-size: 20px;
  }

  .stat-value {
    font-size: 13px;
  }

  .small {
    font-size: 11px;
  }

  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    padding: 10px 0;
  }

  .setting-info {
    margin-right: 0;
  }
}
</style>
